<?php
namespace app\apisell\controller\xcx;

use app\apisell\service\order\OrderService;
use app\BaseController;
use app\common\utils\Res;
use DateInterval;
use DateTime;
use Exception;
use think\facade\Db;
use think\facade\Log;

/**
 * 订单管理
 */
class Order extends BaseController
{
    /**
     * 接收用户订单信息
     *
     * 此函数负责处理用户提交的订单信息，包括订单的创建和数据库的事务处理
     * 它从请求参数中获取订单相关数据，验证用户ID，查询商品信息，
     * 并在数据库中插入订单和订单商品的详细信息
     */
    public function receiveUserOrder()
    {
        // 获取请求参数
        $param = $this->request->post();
        
        // 提取请求参数中的数据
        $userId =  $this->request->id;//获取用户id
        if (empty($userId)){
            return Res::error("用户ID为空");
        }
        // 推广id
        $popu_id = $param['link_yard'] > 0 ? Db::table('xh_sell_popu_link')->where('link_yard',$param['link_yard'])->value('id') : 0;
        $address_id = $param['address_id']; // 用户地址id
        // 生成订单号
        $order_no = 'S' . date('YmdHis') . rand(10000000, 99999999);
        $goods_id = $param['goods_id'];
        $price = $param['price']; // 支付价格
        $number = $param['number']; // 购买数量
        $popu_user_id =  $param['popu_user_yard'] > 0 ? Db::table('xh_sell_popu_user')->where('popu_yard',$param['popu_user_yard'])->value('id') : 0; //推广员ID
        $remark = $param['remark'] ?? '';
        // 验证用户ID是否为空
        if ($userId == 0){
            return Res::error("用户ID为空");
        }
        // 查询商品信息
        $goodsList = Db::table('xh_sell_goods')->where('id',$goods_id)->field('name,price,img,commission')->find();
        if (empty($goodsList)){
            return Res::error("商品不存在");
        }
        // 获取用户当前信息
        $userInfo = Db::table('xh_sell_user')->where('id',$userId)->find();
        if (empty($userInfo)){
            return Res::error("用户不存在");
        }
        // 开始事务
        Db::startTrans();
        
        try {
            $data = [
                'order_no' => $order_no,
                'user_id' => $userId,
                'popu_id'=> $popu_id,
                'belongs_popu_user_id' => $popu_user_id,
                'address_id' => $address_id,
                'remark' => $remark,
                'create_time' => date('Y-m-d H:i:s',time())
            ];
            // 插入订单信息
            $orderId = Db::table('xh_sell_order')->insertGetId($data);
            $data_info = [
                'order_id' => $orderId,
                'goods_id' => $goods_id,
                'title' => $goodsList['name'],
                'price' => $goodsList['price'] ,
                'actual_payment' => $goodsList['price'],
                'image' => $goodsList['img'],
                'number' => $number,
                'commission'=> $goodsList['commission'],
                'create_time' => date('Y-m-d H:i:s',time())
            ];
            // 插入订单商品详细信息
            Db::table('xh_sell_order_goods')->insert($data_info);
            $resOrder = Db::table('xh_sell_order')->where('id',$orderId)->find();
            // 判断是否为推广订单
            if ($popu_id > 0){

                //添加佣金
                $price = Db::table('xh_sell_popu_link')->where(['id'=>$popu_id])->value('link_divide_price');
                $popuUserId = Db::table('xh_sell_popu_user')->where('id',$popu_user_id)->value('popu_user_id');
                //查找上级推广员
                $popuUserInfo = Db::table('xh_sell_user')->where('id',$popuUserId)->find();
                //计算二级推广员佣金
                $total_commission = $goodsList['commission'] - $price['link_divide_price'];
                if ($total_commission < 0){
                    $total_commission = 0;
                }
                //计算并更新一级推广员佣金
                if ($userInfo['is_popu_lever'] == 0  && $popuUserInfo['is_popu_lever'] == 1){
                    Db::table('xh_sell_groups_order')
                        ->where('id',$orderId)
                        ->update(['earnings_level_one'=>$goodsList['commission'],'settle_time'=>date('Y-m-d H:i:s',time())]);

                }elseif ($userInfo['is_popu_lever'] == 0 && $popuUserInfo['is_popu_lever'] == 2){
                    Db::table('xh_sell_groups_order')
                        ->where('id',$orderId)
                        ->update(['earnings_level_two'=>$price['link_divide_price'],'earnings_level_one'=>$total_commission,'settle_time'=>date('Y-m-d H:i:s',time())]);

                }elseif ($userInfo['is_popu_lever'] == 1){
                    Db::table('xh_sell_groups_order')
                        ->where('id',$orderId)
                        ->update(['earnings_level_one'=>$goodsList['commission'],'settle_time'=>date('Y-m-d H:i:s',time())]);
                }elseif ($userInfo['is_popu_lever'] == 2){
                    Db::table('xh_sell_groups_order')
                        ->where('id',$orderId)
                        ->update(['earnings_level_two'=>$price['link_divide_price'],'earnings_level_one'=>$total_commission,'settle_time'=>date('Y-m-d H:i:s',time())]);
                }

                // 使用参数化查询防止SQL注入
                $resDay = Db::table('xh_sell_sys_wechat_pay_disposition')
                    ->where('id', '>', 0)
                    ->find();
                // 获取当前日期，并指定时区
                $effectiveDateTime = new DateTime($resOrder['create_time']);
                // 创建 DateInterval 对象
                $interval = new DateInterval('P' . $resDay['deal_day'] . 'D');
                // 添加有效期
                $expiryDateTime = $effectiveDateTime->add($interval);
                // 格式化到期时间
                $expiryDate = $expiryDateTime->format('Y-m-d H:i:s');
                Db::table('xh_sell_order')->where('id',$orderId)->update(['settle_time'=>$expiryDate]);
                
            }
           
            //同步订单
            OrderService::syncXhOrder($orderId);
            // 提交事务
            Db::commit();
            return Res::ok($resOrder);
        } catch (Exception $e) {
            // 发生错误回滚事务
            Db::rollBack();
            // 记录错误日志
            error_log($e->getMessage());
            return Res::error('创建订单失败'.$e->getMessage());
        }
    }
    /**
     * 获取用户订单列表
     *
     * 本函数用于处理用户订单列表的请求，根据用户ID和类型筛选订单
     * 它首先验证请求参数的完整性，然后根据用户ID和订单类型查询相应的订单列表
     * 如果请求参数不完整或查询过程中发生错误，将抛出异常并返回相应的错误信息
     */
    public function getUserOrderList()
    {
        try {
            // 获取请求参数
            $param = $this->request->post();
            $id =  $this->request->id;//获取用户id
            $type = $param['type'] ?? null;
            // 获取请求参数分页
            $page = isset($param['page']) ? intval($param['page']) : 1;
            $pageSize = isset($param['pageSize']) ? intval($param['pageSize']) : 10;
           // 计算偏移量
            $offset = ($page - 1) * $pageSize;

            // 验证请求参数
            if (empty($id) || empty($type)) {
                throw new Exception("Missing required parameters");
            }
    
            // 根据类型查询订单列表
            $orderList = $this->getOrdersByType($id, $type,$offset,$pageSize);
    
            // 返回查询结果
            return $orderList;
        } catch (Exception $e) {
            // 异常处理
            echo "Error: " . $e->getMessage();
        }
    }
    
    /**
     * 根据类型获取用户订单
     *
     * 本函数通过用户ID和订单类型来查询并返回用户的相关订单信息
     * 订单类型决定了查询的订单状态，例如：进行中、已完成等
     * 如果类型不存在，则返回空数组
     *
     * @param int $userId 用户ID
     * @param int $type 订单类型 1:所有订单；2:进行中；3:已完成；4:已取消；5:已退款
     * @return array 返回订单列表或空数组
     */
    private function getOrdersByType($userId, $type,$offset,$pageSize)
    {
        switch ($type) {
            case 1:
                // 查询所有订单
                $orderList = Db::table('xh_sell_order')
                    ->alias('a')
                    ->leftJoin('xh_sell_order_goods b', 'a.id = b.order_id')
                    ->where('user_id', $userId)
                    ->limit($offset, $pageSize)
                    ->field('a.id,a.order_no,a.state,a.create_time,b.title,b.image,convert(b.price /100,decimal(10,2)) as price,convert(b.actual_payment /100,decimal(10,2)) as actual_payment,b.number,b.goods_id')
                    ->order('create_time desc')
                    ->select();

               $total =  Db::table('xh_sell_order')
                    ->alias('a')
                    ->leftJoin('xh_sell_order_goods b', 'a.id = b.order_id')
                    ->where('user_id', $userId)->count();
                $orderList = [
                    'list' => $orderList,
                    'total' => $total
                ];
                break;
            case 2:
                // 查询待支付的订单
                $orderList = Db::table('xh_sell_order')
                    ->alias('a')
                    ->leftJoin('xh_sell_order_goods b', 'a.id = b.order_id')
                    ->where('user_id', $userId)
                    ->where('state',1)
                    ->field('a.id,a.order_no,a.state,a.create_time,b.title,b.image,convert(b.price / 100,decimal(10,2)) as price,convert(b.actual_payment /100,signed) as actual_payment,b.number,b.goods_id')
                    ->order('create_time desc')
                    ->limit($offset, $pageSize)
                    ->select();
                $total =  Db::table('xh_sell_order')
                    ->alias('a')
                    ->leftJoin('xh_sell_order_goods b', 'a.id = b.order_id')
                    ->where('user_id', $userId)
                    ->where('state',1)
                    ->count();
                $orderList = [
                    'list' => $orderList,
                    'total' => $total
                ];
                break;
            case 3:
                // 查询待发货的订单
                $orderList = Db::table('xh_sell_order')
                    ->alias('a')
                    ->leftJoin('xh_sell_order_goods b', 'a.id = b.order_id')
                    ->where('user_id', $userId)
                    ->where('state',2)
                    ->field('a.id,a.order_no,a.state,a.create_time,b.title,b.image,convert(b.price / 100,decimal(10,2)) as price,convert(b.actual_payment /100,decimal(10,2)) as actual_payment,b.number,b.goods_id')
                    ->order('create_time desc')
                    ->limit($offset, $pageSize)
                    ->select();
                $total =  Db::table('xh_sell_order')
                    ->alias('a')
                    ->leftJoin('xh_sell_order_goods b', 'a.id = b.order_id')
                    ->where('user_id', $userId)
                    ->where('state',2)
                    ->count();
                $orderList = [
                    'list' => $orderList,
                    'total' => $total
                ];
                break;
            case 4:
                // 查询待收货的订单
                $orderList = Db::table('xh_sell_order')
                    ->alias('a')
                    ->leftJoin('xh_sell_order_goods b', 'a.id = b.order_id')
                    ->where('user_id', $userId)
                    ->where('state',3)
                    ->field('a.id,a.order_no,a.state,a.create_time,b.title,b.image,convert(b.price / 100,decimal(10,2)) as price,convert(b.actual_payment /100,decimal(10,2)) as actual_payment ,b.number,b.goods_id')
                    ->order('create_time desc')
                    ->limit($offset, $pageSize)
                    ->select();
                $total =  Db::table('xh_sell_order')
                    ->alias('a')
                    ->leftJoin('xh_sell_order_goods b', 'a.id = b.order_id')
                    ->where('user_id', $userId)
                    ->where('state',3)
                    ->count();
                $orderList = [
                    'list' => $orderList,
                    'total' => $total
                ];
                break;
            case 5:
                // 查询售后的订单
                $orderList = Db::table('xh_sell_order')
                    ->alias('a')
                    ->leftJoin('xh_sell_order_goods b', 'a.id = b.order_id')
                    ->where('user_id', $userId)
                    ->where('state',4)
                    ->field('a.id,a.order_no,a.state,a.create_time,b.title,b.image,convert(b.price / 100,decimal(10,2)) as price,convert(b.actual_payment /100,decimal(10,2)) as actual_payment,b.number,b.refund_status,b.goods_id')
                    ->order('create_time desc')
                    ->limit($offset, $pageSize)
                    ->select();
                $total =  Db::table('xh_sell_order')
                    ->alias('a')
                    ->leftJoin('xh_sell_order_goods b', 'a.id = b.order_id')
                    ->where('user_id', $userId)
                    ->where('state',4)
                    ->count();
                $orderList = [
                    'list' => $orderList,
                    'total' => $total
                ];
                break;
            default:
                // 默认情况下返回空数组
                $orderList = [];
                break;
        }
        // 返回订单列表
        return Res::ok($orderList);
    }
    
    /**
     * 取消订单方法
     * 该方法用于处理用户取消订单的请求，通过接收请求参数，验证参数完整性，
     * 查询并验证订单信息，最后更新订单状态为已取消
     * 
     * @return array 返回操作结果的数组，包含状态和消息
     */
    public function cancelOrder()
    {
        // 接收POST请求参数
        $param = $this->request->post();
        // 提取请求参数中的订单ID和用户ID
        $id = $param['id'] ?? null;
       // $user_id = $param['user_id'] ?? null;
        $user_id =  $this->request->id;//获取用户id

        // 检查订单ID和用户ID是否都已提供
        if (empty($id) || empty($user_id)) {
            // 如果任一参数未提供，则返回错误提示，缺少必要参数
            return Res::error('Missing required parameters');
        }
        
        // 获取指定ID的订单信息
        $orderInfo = Db::table('xh_sell_order')->where('id', $id)->find();
        // 检查订单是否存在
        if (!$orderInfo) {
            // 如果订单不存在，则返回错误提示，未找到订单
            return Res::error('Order not found');
        }
        
        // 验证订单是否属于当前用户
        if ($orderInfo['user_id'] != $user_id) {
            // 如果订单不属于当前用户，则返回错误提示，非法操作
            return Res::error('Invalid operation');
        }
        
        try {
            // 更新订单状态为已取消（state=6）
            $result = Db::table('xh_sell_order')->where('id', $id)->update(['state' => 6]);
            // 检查更新操作是否成功
            if ($result) {
                // 如果成功，则返回成功提示，订单取消成功
                return Res::ok('Order canceled successfully');
            } else {
                // 如果失败，则返回错误提示，订单取消失败
                return Res::error('Failed to cancel order');
            }
        } catch (Exception $e) {
            // 如果操作中出现异常，则返回错误提示，包含异常信息
            return Res::error($e->getMessage());
        }
    }
    
    /**
     * 确认收货
     * 
     * 此方法用于处理订单的确认操作，包括验证订单ID和用户ID，以及更新订单状态
     * 它通过POST请求接收参数，验证这些参数的存在性，并确保订单属于指定的用户
     * 最后，它更新订单的状态表示确认，并返回相应的结果
     */
    public function confirmOrder()
    {
        // 从请求中获取参数
        $param = $this->request->post();
        // 提取订单ID和用户ID，如果不存在则为null
        $id = $param['id'] ?? null;
       // $user_id = $param['user_id'] ?? null;
        $user_id =  $this->request->id;//获取用户id

        // 检查订单ID和用户ID是否都已提供
        if (empty($id) || empty($user_id)) {
            return Res::error('Missing required parameters');
        }
        
        // 根据ID查询订单信息
        $orderInfo = Db::table('xh_sell_order')->where('id', $id)->find();
        
        // 如果找不到订单，返回错误信息
        if (!$orderInfo) {
            return Res::error('Order not found');
        }
        
        // 验证订单是否属于当前用户
        if ($orderInfo['user_id'] != $user_id) {
            return Res::error('Invalid operation');
        }
        
        try {
            // 更新订单状态为已确认（状态码5）
            $result = Db::table('xh_sell_order')->where('id', $id)->update(['state' => 5,'taketime'=>date('Y-m-d H:i:s',time())]);
            
            // 根据更新结果返回成功或失败信息
            if ($result) {
                //同步订单
                OrderService::syncXhOrder($id);
                return Res::ok('Order confirmed successfully');
            } else {
                return Res::error('Failed to confirm order');
            }
        } catch (Exception $e) {
            // 捕获并返回任何异常信息
            return Res::error($e->getMessage());
        }
    }
    
    /**
     * 处理订单退款请求
     * 
     * 本函数负责处理订单的退款请求，包括更新订单状态、记录退款信息等操作
     * 它从输入参数中获取订单ID、用户ID、退款原因和商品ID，然后执行退款流程
     * 如果必要参数缺失，或者订单不存在，将返回相应的错误信息
     * 退款成功后，将更新订单状态，并在退款记录表中插入一条新记录
     * 
     * @return array 包含退款结果和相应消息的数组
     */
    public function refundOrder()
    {
        // 获取请求参数
        $param = $this->request->post();
        $id = $param['id'] ?? 0;
        $user_id =  $this->request->id;//获取用户id
        //$user_id = $param['user_id'] ?? null;
        $refund_reason = $param['refund_reason'] ?? 0;
        $goods_id = $param['goods_id'] ?? 0;
        $order_type = $param['order_type']; //订单类型 1:普通订单 2:拼团订单
        
        // 检查订单ID和用户ID是否都已提供
        if (empty($id) || empty($user_id)) {
            return Res::error('Missing required parameters');
        }
        if ($order_type == 1){
            // 根据ID查询订单信息
            $orderInfo = Db::table('xh_sell_order')->where('id', $id)->find();
            if (empty($orderInfo)){
                return Res::error('Order not found');
            }
            // 根据ID查询订单商品信息
            $goodsInfo = Db::table('xh_sell_goods')->where('id', $goods_id)->find();
            if (empty($goodsInfo)){
                return Res::error('Goods not found');
            }
            // 根据ID查询订单支付信息
            $payInfo = Db::table('xh_sell_order_pay')->where('order_id', $id)->find();
            if (empty($payInfo)){
                return Res::error('Payment information not found');
            }
            // 如果找不到订单，返回错误信息
            if (!$orderInfo) {
                return Res::error('Order not found');
            }
            try {
                Db::startTrans();
                // 更新订单状态为已退款
                Db::table('xh_sell_order')->where('id', $id)->update(['state' => 4]);
                Db::table('xh_sell_order_goods')->where('order_id', $id)->update(['refund_status' => 1]);
                // 准备退款记录数据
                $data = [
                    'order_id' => $id,
                    'user_id' => $user_id,
                    'order_pay_id' => $payInfo['id'],
                    'goods_id' => $goods_id,
                    'order_no' => $orderInfo['order_no'],
                    'price' => $goodsInfo['price'],
                    'order_type' => $order_type,
                    'reason' => $refund_reason,
                    'create_time' => date('Y-m-d H:i:s', time()),
                ];
                // 插入退款记录
                $result = Db::table('xh_sell_refund')->insert($data);
                // 提交事务
                Db::commit();
                // 根据更新结果返回成功或失败信息
                if ($result) {
                    return Res::ok('Order refunded successfully');
                } else {
                    return Res::error('Failed to refund order');
                }
            } catch (Exception $e) {
                // 发生错误回滚事务
                Db::rollBack();
                // 如果发生异常，返回错误信息
                return Res::error($e->getMessage());
            }
            
        }elseif ($order_type == 2){
            // 根据ID查询订单信息
            $orderInfo = Db::table('xh_sell_groups_order')->where('id', $id)->find();
            if (empty($orderInfo)){
                return Res::error('订单未找到');
            }
            // 根据ID查询订单商品信息
            $goodsInfo = Db::table('xh_sell_groups_order_goods')->where('order_id', $id)->find();
            if (empty($goodsInfo)){
                return Res::error('订单商品未找到');
            }
            // 根据ID查询订单支付信息
            $payInfo = Db::table('xh_sell_order_pay')->where('order_id', $id)->where('type', 2)->find();
            if (empty($payInfo)){
                return Res::error('订单支付信息未找到');
            }
            
            try {
                Db::startTrans();
                // 更新订单状态为已退款
                Db::table('xh_sell_groups_order')->where('id', $id)->update(['state' => 5]);
                Db::table('xh_sell_groups_order_goods')->where('order_id', $id)->update(['refund_status' => 1]);
                // 准备退款记录数据
                $data = [
                    'order_id' => $id,
                    'user_id' => $user_id,
                    'order_pay_id' => $payInfo['id'],
                    'goods_id' => $goodsInfo['goods_sku_id'],
                    'order_no' => $orderInfo['order_no'],
                    'price' => $goodsInfo['price'],
                    'order_type' => $order_type,
                    'reason' => $refund_reason,
                    'create_time' => date('Y-m-d H:i:s', time()),
                ];
                // 插入退款记录
                $result = Db::table('xh_sell_refund')->insert($data);
                
                // 提交事务
                Db::commit();
                // 根据更新结果返回成功或失败信息
                if ($result) {
                    return Res::ok('Order refunded successfully');
                } else {
                    return Res::error('Failed to refund order');
                }
            } catch (Exception $e) {
                // 发生错误回滚事务
                Db::rollBack();
                // 如果发生异常，返回错误信息
                return Res::error($e->getMessage());
            }
        }
    }
    //取消退款
     public function cancelRefund()
    {
        $param = $this->request->post();
        $id = $param['id'] ?? null;
       //  $user_id = $param['user_id'] ?? null;
        $user_id =  $this->request->id;//获取用户id

        // 验证输入参数
        if (!is_numeric($id) || !is_numeric($user_id)) {
            return Res::error('Invalid parameter types');
        }
    
        // 检查订单ID和用户ID是否都已提供
        if (empty($id) || empty($user_id)) {
            return Res::error('Missing required parameters');
        }
    
        Db::StartTrans();
        try {
            $resultS = Db::table('xh_sell_refund')->where('order_id', $id)->update(['state' => 4]);
            if (!$resultS) {
                throw new Exception('Failed to update xh_sell_refund');
            }
    
            $result = Db::table('xh_sell_order_goods')->where('order_id', $id)->update(['refund_status' => 4]);
            if (!$result) {
                throw new Exception('Failed to update xh_sell_order_goods');
            }
            $resulter = Db::table('xh_sell_order')->where('id', $id)->update(['state' => 3]);
            if (!$resulter) {
                throw new Exception('Failed to update xh_sell_order');
            }
            Db::commit();
            return Res::ok('Refund canceled successfully');
        } catch (Exception $e) {
            Db::rollBack();
            Log::error('General error: ' . $e->getMessage());
            return Res::error($e->getMessage());
        }
    }

      
}
